template.defaults.imports.splitImages = function (imgsStr) {
    var imgs = imgsStr.split(',');
    template.defaults.imports.imgs = imgs;
};

template.defaults.imports.getVideoInfo = function (videoId) {
    $.ajaxSettings.async = false;
    $.get('/listSnapshots',{
        videoId:videoId,
    },function(result){
        if (result.code == 100){
            var url = result.data.MediaSnapshot.Snapshots.Snapshot[0].Url;
            $.get('/getPlayInfo?videoId=' + videoId,function(result){
                var playVideo = '';
                for (var i = 0;i < result.data.length; i++){
                    if (result.data[i].Format == 'mp4'){
                        playVideo = result.data[i].PlayURL;
                        break;
                    }
                }
                template.defaults.imports.video = {
                    playUrl:playVideo,
                    imgUrl:url
                };
                $.ajaxSettings.async = true;
            });
        }
    });
};

template.defaults.imports.CountdownTime = function (factEndDate) {
    var timestamp = (new Date()).valueOf();
    return factEndDate - timestamp;
};

template.defaults.imports.TimestampToTime = function (timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    return Y + M + D + h + m ;
};

template.defaults.imports.ellipsisName = function (name) {
    var strLen = name.length;
    if (strLen > 2){
        name = name.substr(1); //删除第一个字符
        name = name.substr(0, name.length - 1);
        return '*' + name + '*';
    } else if (strLen > 1){
        return name.substr(0, 1) + '*';
    } else {
        return name;
    }
};

template.defaults.imports.sendTime = function (createDate) {
    var timestamp = (new Date()).valueOf();
    var diffiTime = timestamp - createDate;
    //计算天
    var day = Math.floor(diffiTime / (1000 * 60 * 60 * 24));
    var surplus = diffiTime % (1000 * 60 * 60 * 24);
    var hour = Math.floor(surplus / (1000 * 60 * 60));
    surplus = surplus % (1000 * 60 * 60);
    var minute = Math.floor(surplus / (1000 * 60));

    return (day ? day + '天' : '') + (hour ? hour + '小时' : '') + (minute ? minute + '分' : '') + '前';
};

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

var sharing = false;
var addPriceOnce = 0;
var addPriceTwice = 0;
//查询商品详情
var productDetail = {};
$.post('/antique/api/mallProduct/web/query', {
    /* global getCookie visitUrl*/
    token: getCookie('token'),
    /* global id */
    id: id
}, function (result) {
    /* global template */
    var html = template('detail', result);
    productDetail = result.data;
    console.log(productDetail);

    //设置分享
    $.post('/antique/api/wxApi/getticket', {
        url: window.location.href
    }, function (result) {
        //access_token = result.data.access_token;
        wx.config({
            debug: false,
            appId: result.data.appid,
            timestamp: result.data.timestamp,
            nonceStr: result.data.noncestr,
            signature: result.data.signature,
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
            ]
        });
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
                ],
                success: function (res) {
                    //alert(JSON.stringify(res));
                    //alert(JSON.stringify(res.checkResult.getLocation));
                    if (res.checkResult.getLocation == false) {
                        alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                        return;
                    } else {
                        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，
                        // 则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                        //分享到朋友圈
                        wx.onMenuShareTimeline({
                            title:'【' + productDetail.name + '】' + '【' + productDetail.sizeDesc + '】' + productDetail.detailsDesc, // 分享标题
                            link:window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            desc: productDetail.detailsDesc, // 分享描述
                            imgUrl:productDetail.coverImage, // 分享图标
                            success: function () {
                                // 用户点击了分享后执行的回调函数
                            },
                        });
                        //分享给朋友
                        wx.onMenuShareAppMessage({
                            title:'【' + productDetail.name + '】' + '【' + productDetail.sizeDesc + '】' + productDetail.detailsDesc, // 分享标题
                            link:window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            desc: productDetail.detailsDesc, // 分享描述
                            imgUrl: productDetail.coverImage, // 分享图标
                            type: '', // 分享类型,music、video或link，不填默认为link
                            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                            success: function () {
                            // 用户点击了分享后执行的回调函数
                            }
                        });
                    }
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            alert("验证失败，请重试！");
            wx.closeWindow();
        });
    });
    var _result = result;
    $('.bondMoney').each(function(){
        $(this).text('￥' + result.data.bondMoney);
    });
    $('.nowPrice').each(function(){
        $(this).text('￥' + result.data.nowPrice); 
    });
    $('.bidIncrementPrice').each(function(){
        $(this).text('￥' + result.data.bidIncrementPrice); 
    });
    if(result.data.fixedPrice){
        $('.goPrice').text('￥' + result.data.fixedPrice);
    } else {
        $('#standard_offer .op .gobuy,#custom-price .op .gobuy').hide();
        $('#confirmPrice,#customConfirmPrice').css({
            width:'7.7rem',
            marginLeft:0
        });
    }
    var timestamp = (new Date()).valueOf();
    $('#dialog_count_time').attr('time',result.data.planEndDate - timestamp);
    //加一手价格的价格
    addPriceOnce = result.data.nowPrice + 1 * result.data.bidIncrementPrice;
    $('#addOnePrice').attr({price:addPriceOnce}).text(' ￥' + addPriceOnce);
    //加二手价格的价格
    addPriceTwice = result.data.nowPrice + 2 * result.data.bidIncrementPrice;
    $('#addTwoPrice').attr({price:addPriceTwice}).text(' ￥' + addPriceTwice);
    //计算最低价
    var floorPrice = parseInt(result.data.nowPrice) + parseInt(result.data.bidIncrementPrice);
    document.getElementById('detail-content').innerHTML = html;
    $("#isAgent").bind("click", function () {
        if ($("input[name='isAgent']").val() == "off"){
            $("input[name='isAgent']").val("on");
        } else {
            $("input[name='isAgent']").val("off");
        }
    });
    $('#customPrice').attr('placeholder' , '您的最低出价不得低于' + floorPrice + '元');
    //确认出价
    $('#confirmPrice').click(function(){
        var sendPrice = parseInt($('.go-prices .selected .price').attr('price'));
        if (floorPrice > sendPrice){
            $.toast("出价不得低于" + floorPrice + '元', "forbidden");
            return false;
        }
        /* global isInteger */    
        //普通出价
        if (sendPrice && isInteger(sendPrice)){
            $.post('/antique/api/productBidLog/bid',{
                bidType:1,
                bidCount:1,
                bidPrice:sendPrice,
                productId:id,
                token:getCookie('token')
            },function(result){
                $.toast(result.message, function() {
                    window.location.reload();
                });
            });            
        } else {
            $.toast("必须输入数字", "forbidden");
        }  
    });
    //自定义金额确认出价
    $('#customConfirmPrice').click(function(){
        var sendPrice = parseInt($('#customPrice').val());
        if (floorPrice > sendPrice){
            $.toast("出价不得低于" + floorPrice + '元', "forbidden");
            return false;
        }
        /* global isInteger */    
        //普通出价
        if (sendPrice && isInteger(sendPrice)){
            $.post('/antique/api/productBidLog/bid',{
                bidType:1,
                bidCount:1,
                bidPrice:sendPrice,
                productId:id,
                token:getCookie('token')
            },function(result){
                $.toast(result.message, function() {
                    window.location.reload();
                });
            });            
        } else {
            $.toast("必须输入数字", "forbidden");
        }  
    });
    //确认支付消保金
    $('#confirmBondPay').click(function(){
        var type = $("input[name='radioPay']:checked").val();
        //等于1为钱包支付，等于2为微信支付
        /* global hex_md5 isMiniProgram wx*/
        if (type == 1){
            passwordPay(id,1);
        } else if (type == 2){
            if ( isMiniProgram () ) {//小程序就跳转小程序支付
                var params = {
                    type: 130,//支付类型
                    id: id,//关联id
                    payMoney: result.data.bondMoney,//支付金额
                    content:'缴纳店铺消保金' + result.data.bondMoney,//订单说明
                    jumpUrl:'/pages/auctionCollectDetail',//支付成功后跳转地址  为空返回当前页面 不可以带 ? 和 &
                };
                wx.miniProgram.navigateTo({
                    url: "/pages/pay/index?params=" + JSON.stringify(params)
                });
            } else {
                /* global getCookie servicePay*/
                $.post('/antique/api/onlinePay/wxpay/create_wxpay', {
                    token:getCookie('token'),
                    type:130,
                    appSource:1,
                    keyId:id,
                    money:servicePay(result.data.bondMoney),
                    content:'缴纳店铺消保金' + result.data.bondMoney
                }, function (result) {
                    var appId = result.data.appid;
                    var nonceStr = result.data.nonce_str;
                    var prepay_id = result.data.prepay_id;
                    var mch_id = result.data.mch_id;
                    /* global goWeiPay */
                    goWeiPay(appId,nonceStr,prepay_id,mch_id);
                });
            }
        }
    });
    $('.cdetail-top .cdetail-top-auth time[sign="unmake"]').each(function () {
        $(this).removeAttr('sign');
        /* global Countdown Aliplayer*/
        Countdown($(this).attr('time'), $(this));
    });
    $(".swiper-container").swiper({
        loop: true
    });
    var images = result.data.showImages.split(',');
    $(".swiper-slide").click(function() {
        var index = $(this).data('swiper-slide-index');
        var playerContainer = $('<div></div>').attr('id','playerContainer').css({
            position:'fixed',
            width:'100%',
            height:'100%',
            display:'none',
            top: '0',
            zIndex:'9999'
        }).appendTo(window.document.body);
        if ($('.swiper-slide[data-swiper-slide-index="' + index + '"]').hasClass('video')){
            var playUrl = $('.swiper-slide[data-swiper-slide-index="' + index + '"]').attr('data-url');
            //$.get('/log',{info:'playUrl => ' + playUrl});
            //$.get('/log',{info:'playerContainer.length => ' + $('#playerContainer').length});
            var player = new Aliplayer({
                "id": "playerContainer",
                "source": playUrl,
                "width": "100%",
                "height": "500px",
                "autoplay": true,
                "isLive": false,
                "rePlay": true,
                "playsinline": true,
                "preload": true,
                "controlBarVisibility": "hover",
                "useH5Prism": true
            }, function (player) {
                player._switchLevel = 0;
                console.log("播放器创建了。");
            });
            var closeVideo = $('<svg id="closeVideo" t="1552392959791" class="icon" style="width:0.8rem;height:0.8rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>');
            playerContainer.append(closeVideo).show();
            closeVideo.click(function(){
                var _parent = $(this).parent();
                player.stop();
                _parent.remove();
            });
        } else {
            var currentUrl = $('.swiper-slide[data-swiper-slide-index="' + index + '"] img').attr('data-url');
            for (var i = 0;i < images.length;i++){
                images[i] = images[i];
            }
            wx.previewImage({
                current: currentUrl, // 当前显示图片的http链接
                urls: images // 需要预览的图片http链接列表
            });
        }        
    });
    var shopId = $('input[name="shopId"]').val();

    //开始分享
    $('#share').click(function(){
        $("#copyTtml").text('复制链接');
        $("#shareBottom").popup();
        


        // if (!sharing){
        //     sharing = true;

        //     $.post('/antique/api/wxApi/getticket', {
        //         url: window.location.href
        //     }, function (result) {
        //         wx.config({
        //             debug: false,
        //             appId: result.data.appid,
        //             timestamp: result.data.timestamp,
        //             nonceStr: result.data.noncestr,
        //             signature: result.data.signature,
        //             jsApiList: [
        //                 // 所有要调用的 API 都要加到这个列表中
        //                 'checkJsApi',
        //                 'updateAppMessageShareData' //朋友圈
        //             ]
        //         });
        //         wx.ready(function () {
        //             wx.checkJsApi({
        //                 jsApiList: [
        //                     'updateAppMessageShareData' //朋友圈
        //                 ],
        //                 success: function (res) {
        //                     //alert(JSON.stringify(res));
        //                     //alert(JSON.stringify(res.checkResult.getLocation));
        //                     if (res.checkResult.getLocation == false) {
        //                         alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
        //                         return;
        //                     } else {
        //                         shareing();
        //                     }
        //                 }
        //             });
        //         });
        //         wx.error(function (res) {
        //             // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        //             alert("验证失败，请重试！");
        //             wx.closeWindow();
        //         });
        //     }); 
        // }
    });

    //s生成分享图片
    $("#openqrPic").click(function(){  
        $("#sharePic").popup();
        $(".topReturn").hide();
        createCanvas(productDetail);
    });
    
    function shareing(){
        wx.updateAppMessageShareData({ 
            title: '古今分享', // 分享标题
            desc: _result.data.name, // 分享描述
            link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: _result.data.coverImage + '?x-oss-process=image/resize,w_200,h_200', // 分享图标
            success: function () {
              // 设置成功
            }
        });
    }
    //开始举报
    $('#report_target').click(function(){
        $('textarea[name="report-content"]').val('');
        $("#report").popup();
    });
    $('#confirmReport').click(function(){
       var text = $('textarea[name="report-content"]').val();
       if(text.length >= 20 && text.length <= 200){
            $.post('/antique/api/mallComplaint/complaint', {
                /* global id */
                keyId: id,
                type:2,
                content:text,
                token:getCookie('token')
            },function(data){
                $.toast('举报成功，谢谢您对我们的支持!');
            });
       } else {
            $.toast('对不起，您输入的举报内容文字不在20-200个字内！请修改后上传。');
       }
    });
    $('textarea[name="report-content"]').keyup(function(e){
        var text = $(this).val();
        $('.weui-textarea-counter span').text(text.length);
        if(text.length < 20){
            $('.weui-textarea-counter span').removeClass('green').addClass('red');
        } else if(text.length > 200){
            $('.weui-textarea-counter span').removeClass('green').addClass('red');
        } else {
            $('.weui-textarea-counter span').removeClass('red').addClass('green');
        }
    });
    //一口价直接购买
    $('.gobuy').click(function(){
        setOrderDetail(result.data);
    });
    //在出价框显示倒计时
    Countdown($('#dialog_count_time').attr('time'), $('#dialog_count_time'));    
    //渲染关注用户信息
    getFollowUsers();

    //查询是否已缴纳消保金
    $.post('/antique/api/productBondLog/check_bondpay',{
        productId:id,
        token:getCookie('token')
    },function(result){
        var isPayBond = false;
        if (result.code == 1){
            isPayBond = true;
        } else if (result.code == 0){
            isPayBond = result.data.bondPay;
        }
        var html = template('offer-content', {
            isPayBond:isPayBond
        });
        document.getElementById('offer').innerHTML = html;
        $('#standard_offer_target').unbind('click').bind('click',function(){
            setAuctionPrice();
        });    
        $('#pay_deposit_target').unbind('click').bind('click',function(){
            $("#pay_deposit").popup();
        });
    });

    //查询用户的信息
    $.post('/antique/api/sysUser/query_user_by_userId',{
        userId:getCookie('userId')
    },function(result){
        //如果是管理员就可以进行推荐
        if(result.data.onlineManage == 1){
            $('#recommend').css('display','inline').click(function(){
                $.confirm("您确认要推荐该藏品吗?", "确认推荐?", function() {
                    $.post('/antique/api/mallProduct/manage/recommend_product',{
                        token:getCookie('token'),
                        id:id,
                        type:1
                    },function(result){
                        $.toast('推荐成功!',1000);
                    });
                }, function() {
                    //取消操作
                });
            });

            $('#unrecommend').css('display','inline').click(function(){
                $.confirm("您确认要取消推荐该藏品吗?", "确认取消推荐?", function() {
                    $.post('/antique/api/mallProduct/manage/recommend_product',{
                        token:getCookie('token'),
                        id:id,
                        type:2
                    },function(result){
                        $.toast('取消推荐成功!',1000);
                    });
                }, function() {
                    //取消操作
                });
            });
        }
    });

    //查询最近的藏品及其专场信息
    function querypaimaiList(){
        $.post('/antique/api/mallProduct/web/query_list', {
            start: 0,
            limit: 10,
            queryType: 1,
            shopId:shopId
        }, function (result) {
            /* global template */
            var leftList = [];
            var rightList = [];
            if (result.data.list){
                for(var i = 0;i<result.data.list.length;i++){
                    if (i%2 == 0){
                        leftList.push(result.data.list[i]);
                    } else {                        
                        rightList.push(result.data.list[i]);
                    }
                }
            }

            if(result.data.list && result.data.list.length > 0){
                /* global template */
                document.getElementById('paimai-left-list-content').innerHTML = template('paimai-left-list', {list:leftList});
                document.getElementById('paimai-right-list-content').innerHTML = template('paimai-right-list', {list:rightList}); 
                $('.weipai-list .lot .info .price .time time[sign="unmake"]').each(function () {
                    $(this).removeAttr('sign');
                    /* global Countdown */
                    Countdown($(this).attr('time'), $(this));
                });
            } else {
                $('.weui-navbar__item').eq(0).hide();
                $('#tab1').hide();
            }
        });
    }

    function queryyijiaList(){
        $.post('/antique/api/mallProduct/web/query_list', {
            start: 0,
            limit: 10,
            queryType: 2,
            shopId:shopId
        }, function (result) {
            /* global template */
            var leftList = [];
            var rightList = [];
            if (result.data.list){
                for(var i = 0;i<result.data.list.length;i++){
                    if (i%2 == 0){
                        leftList.push(result.data.list[i]);
                    } else {                        
                        rightList.push(result.data.list[i]);
                    }
                }
            }

            if(result.data.list && result.data.list.length > 0){
                /* global template */
                document.getElementById('yijia-left-list-content').innerHTML = template('yijia-left-list', {list:leftList});
                document.getElementById('yijia-right-list-content').innerHTML = template('yijia-right-list', {list:rightList}); 
                $('#tab2 .lot .info .price .time time[sign="unmake"]').each(function () {
                    $(this).removeAttr('sign');
                    /* global Countdown */
                    Countdown($(this).attr('time'), $(this));
                });
            } else {
                $('.weui-navbar__item').eq(1).hide();
                $('#tab2').hide();
            }
        });
    }

    function querySpecial(){
        $.post('/antique/api/mallAuction/web/query_list', {
            start: 0,
            limit: 10,
            source: 2,
            showProduct:1,
            shopId:shopId
        }, function (result) {
            if(result.data.list && result.data.list.length > 0){
                document.getElementById('zc-content').innerHTML = template('zc', result.data);
            } else {
                $('.weui-navbar__item').eq(2).hide();
                $('#tab3').hide();
            }
        });
    }

    querypaimaiList();
    queryyijiaList();
    querySpecial();
});

function selectPayStyle(obj){
    switch(parseInt($(obj).val())){
        case 1:
            //自定义价格，价格由自己设置任意整形价格
            $('input[name="sentPrice"]').attr("disabled", false).val('');
            break;
        case 2:
            //加一手价格            
            $('input[name="sentPrice"]').attr("disabled", true).val(addPriceOnce);
            break;
        case 3:
            //加两手价格            
            $('input[name="sentPrice"]').attr("disabled", true).val(addPriceTwice);
            break;
        case 4:
            //代理出价    
            $('input[name="sentPrice"]').attr("disabled", false).val('');
            break;
        default:
            break;
    }
}

//查询出价记录
$.post('/antique/api/productBidLog/query_list', {
    /* global id */
    productId: id,
    start:0,
    limit:200,
    bidType:1
}, function (result) {
    $('#offerCount').text(result.data.list ? result.data.list.length : 0);
    /* global template */
    var html = template('cdetail-price-list', result);
    document.getElementById('cdetail-price-list-content').innerHTML = html;
});

//是否收藏
$.post('/antique/api/userProductCollection/check_collection',{
    productId:id,
    token:getCookie('token')
},function(result){
    var isColl = result.data.collection;
    if (isColl){
        $('.cdetail-bottom .cdetail-icon-item').eq(2).addClass('selected');
    } else {
        $('.cdetail-bottom .cdetail-icon-item').eq(2).removeClass('selected');
    }
});

//收藏确认或取消
$('.cdetail-bottom .cdetail-icon-item').eq(2).click(function(){
    if ($(this).hasClass('selected')){
        //取消收藏
        collProduct(false);
        $(this).removeClass('selected');
    } else {
        //开始收藏
        collProduct(true);
        $(this).addClass('selected');
    }
});

//私信聊天
$('.cdetail-bottom .cdetail-icon-item').eq(1).click(function(){
    var userId = $('input[name="userId"]').val();
    if(checkUserMe(userId)){
        $.toast('自己和自己不能聊天', "cancel");
    } else {
        visitUrl('/chat?charToUser=' + userId + '&productId=' + id,true);
    }
    
});

//跳转店铺
$('.cdetail-bottom .cdetail-icon-item').eq(0).click(function(){
    var shopId = $('input[name="shopId"]').val();
    visitUrl('/shop/detail?id=' + shopId,true);
});

function collProduct(isColl){
    $.post('/antique/api/userProductCollection/set_collection',{
        productId:id,
        operType:isColl ? 1 : 2,
        token:getCookie('token')
    },function(result){
        if(result.code != 1){
            if (isColl){
                $.toast('关注成功');
                followUserCount(1);
            } else {
                $.toast('取消关注成功','cancel');
                followUserCount(-1);
            }
        } else {
            $.toast(result.message);
            $('.cdetail-bottom .cdetail-icon-item').eq(2).removeClass('selected');
        }
        getFollowUsers();
    });
}

//增加访问足迹
$.post('/antique/api/userFootPrint/view_product',{
    productId:id,
    token:getCookie('token')
},function(){
    
});

/**读取关注用户信息 */
function getFollowUsers(){
    $.post('/antique/api/userProductCollection/query_user_list',{
        productId:id,
        token:getCookie('token'),
        start:0,
        limit:20
    },function(result){
        document.getElementById('followUsers-list-content').innerHTML = template('followUsers-list', {list:result.data.list});
    });
}

/* global timeToTimestamp submitAdd*/
// type 1.保证金支付 2.一口价支付
function passwordPay (id,type) {
    /* global havePayPwd */
    havePayPwd (function(havePwd) {
        if (havePwd) {
            $.modal({
                title: "请输入支付密码",
                text: '<input class="weui-input weui-prompt-input" type="password" id="password"  placeholder="没有设置密码可不填" />',
                buttons: [ 
                    { text: "取消", className: "default" },
                    { text: "确定", onClick: 
                        function(){
                            var password = $("#password").val();
                            var params = {};
                            params.id = id;
                            params.token = getCookie('token');
                            var time = timeToTimestamp(new Date());
                            if (password == '') {
                                params.payPass = hex_md5(time + '').toUpperCase(); 
                            } else {
                                var passwords = hex_md5(password).toUpperCase();
                                params.payPass = hex_md5(passwords + time).toUpperCase();
                            }
                            params.time = time;
                            params.type = type;
                            params.productId = id;
                            submitAdd(params);
                        }
                    }
                ]
            });
        } else {
            var password = '';
            var params = {};
            params.id = id;
            params.token = getCookie('token');
            var time = timeToTimestamp(new Date());
            if (password == '') {
                params.payPass = hex_md5(time + '').toUpperCase(); 
            } else {
                var passwords = hex_md5(password).toUpperCase();
                params.payPass = hex_md5(passwords + time).toUpperCase();
            }
            params.time = time;
            params.type = type;
            params.productId = id;
            submitAdd(params);
        }
    });
}

/** 提交支付密码进行保证金支付 */
function submitAdd(params){
    if(params.type == 1){
        $.ajax({
            type:'POST',
            url:"/antique/api/productBondLog/pay_bond_for_bid",
            data: params,
            dataType:"json",
            success:function(res){
                if (res.code == 0){
                   // window.location.href = document.referrer;
                    $.toast("支付保证金成功!",function(){
                        window.location.reload();
                    },1000);
                } else {
                    $.toast(res.message, "cancel");
                }            
            }
        });
    } else {
        $.ajax({
            type:'POST',
            url:"/antique/api/mallOrder/user/buy_for_fixed_price",
            data: params,
            dataType:"json",
            success:function(res){
                if (res.code == 0){
                   // window.location.href = document.referrer;
                    $.toast("支付成功!");
                 } else {
                    $.toast(res.message, "cancel");
                }            
            }
        });
    }
}

$('.go-prices .item').click(function(){
    if(!$(this).hasClass('other-price')){
        $('.go-prices .item').removeClass('selected');
        $(this).addClass('selected');
    }
});

$('.go-prices .other-price').click(function(){
    $("#custom-price").popup();
});

//设置竞拍价格
function setAuctionPrice(){
    $("#standard_offer").popup();
    $('.go-prices .item').removeClass('selected');
    $('.popup-bottom .weui-popup__modal .close').unbind('click').bind('click',function(){
        
    });
}

//确认一口价支付
function setPricePay(money,productId){
    $('#pay_price .total_pay').text('￥' + money + '.00');
    $('#confirmPricePay').unbind('click').bind('click',function(){
        var type = $("#pay_price input[name='fastRadioPay']:checked").val();
        //等于1为钱包支付，等于2为微信支付
        /* global hex_md5 isMiniProgram wx*/
        if (type == 1){
            passwordPay(productId,2);
        } else if (type == 2){
            if ( isMiniProgram () ) {//小程序就跳转小程序支付
                var params = {
                    type: 112,//支付类型
                    id: productId,//关联id
                    payMoney: money,//支付金额
                    content:'购买' + productDetail.name + '花费' + money + '.00元',//订单说明
                    jumpUrl:'/pages/auctionCollectDetail',//支付成功后跳转地址  为空返回当前页面 不可以带 ? 和 &
                };
                wx.miniProgram.navigateTo({
                    url: "/pages/pay/index?params=" + JSON.stringify(params)
                });
            } else {
                /* global getCookie servicePay*/
                $.post('/antique/api/onlinePay/wxpay/create_wxpay', {
                    token:getCookie('token'),
                    type:112,
                    appSource:1,
                    keyId:productId,
                    money:servicePay(money),
                    content:'购买' + productDetail.name + '花费' + money + '.00元'
                }, function (result) {
                    var appId = result.data.appid;
                    var nonceStr = result.data.nonce_str;
                    var prepay_id = result.data.prepay_id;
                    var mch_id = result.data.mch_id;
                    /* global goWeiPay */
                    goWeiPay(appId,nonceStr,prepay_id,mch_id);
                });
            }
        }
    });
    $("#pay_price").popup();
}

//设置订单详情
function setOrderDetail(product,address){
    $("#confirmOrder").popup();
    $('#confirmOrder .header .return').unbind('click').bind('click',function(){
        
    });
    $('#confirmOrder .antiques .antique .product-img').attr({
        'style':'background:url(' + product.coverImage + '?x-oss-process=image/resize,w_500) no-repeat 0 center;background-size: 100% auto;'
    });
    $('#confirmOrder .shop .shopImg').attr({
        'style':'background:url(' + product.shopDetail.image + '?x-oss-process=image/resize,w_200) no-repeat 0 center;background-size: 100% auto;'
    });
    $('#confirmOrder .shop .shopName').text(product.shopDetail.name);
    $('#confirmOrder .antiques .antique .product-title').text(product.name);
    $('#confirmOrder .antiques .antique .product-price .price').text('￥' + product.fixedPrice + '.00');
    if(product.logisticsFee && product.logisticsFee > 0){
        $('#confirmOrder .distri .postage').text(product.logisticsFee + '.00');
    } else {
        $('#confirmOrder .distri .postage').text('包邮');
    }
    $('#confirmOrder .op .info .total').text('￥' + (product.fixedPrice + product.logisticsFee) + '.00');
    //直接支付
    $('#confirmOrder .op button').unbind('click').bind('click',function(){        
        //先生成订单后支付
        /**$.post('/antique/api/mallOrder/user/buy_for_fixed_price',{
            token:getCookie('token'),
            productId:product.id
        },function(result){
            var receiveAddressId = $('#confirmOrder .receiving').data('id');
            var orderId = result.data.orderId;
            //下单后绑定收货地址
            $.post('/antique/api/mallOrder/user/order_update_detail',{
                token:getCookie('token'),
                id:orderId,
                receiveAddressId:receiveAddressId
            },function(result){
                setPricePay(product.fixedPrice + product.logisticsFee,orderId);  
            });
        }) */
        
        $.post('/antique/api/mallOrder/user/compute_for_fixed_price',{
            token:getCookie('token'),
            productId:product.id
        },function(result){
            var receiveAddressId = $('#confirmOrder .receiving').data('id');
            var money = result.data.money;
            
            setPricePay(money,product.id); 
        })
    });
    //查看默认地址
    if(address){
        $('#confirmOrder .receiving .info .contact .name').text(address.name);
        $('#confirmOrder .receiving .info .contact .tel').text(address.phone);
        $('#confirmOrder .receiving .info .address').text(address.areanames + address.address);
        $('#confirmOrder .receiving').attr('data-id',address.id);
    } else {
        $.post('/antique/api/userAddress/query_list',{
            token:getCookie('token'),
            start:0,
            limit:20
        },function(result){
            if(result.data && result.data.list && result.data.list.length >0){
                for(var i=0;i<result.data.list.length;i++){
                    if(result.data.list[i].isDefault == 1){
                        var obj = result.data.list[i];
                        $('#confirmOrder .receiving .info .contact .name').text(obj.name);
                        $('#confirmOrder .receiving .info .contact .tel').text(obj.phone);
                        $('#confirmOrder .receiving .info .address').text(obj.areaNames + obj.address);
                        $('#confirmOrder .receiving').attr('data-id',obj.id);
                    }
                }
            } else {
                $('#confirmOrder .receiving .info .contact .name').text('您还没有添加任何收货地址');
                $('#confirmOrder .receiving .info .address').text('请单击进入管理收货地址页进行添加收货地址');
            }
        });
    }
    $('#confirmOrder .receiving').unbind('click').bind('click',function(){
        setAddressList();
    });
}

//设置收货地址列表
function setAddressList(){
    $("#selectAddress").popup();
    $('#selectAddress .header .return').unbind('click').bind('click',function(){
        
    });
    
    $.post('/antique/api/userAddress/query_list',{
        token:getCookie('token'),
        start:0,
        limit:20
    },function(result){
        var html = template('address-list', result.data);
        $('#selectAddress .address-list').html(html);

        $('#addAddress').unbind('click').bind('click',function(){
            setAddAddress('',(result.data && result.data.list && result.data.list.length > 0)?true:false);
        });
        $('#selectAddress .address-list > .address').unbind('click').bind('click',function(){
            var _this = this;
            setOrderDetail(productDetail,{
                name:$(_this).data('name'),
                phone:$(_this).data('phone'),
                areanames:$(_this).data('areanames'),
                address:$(_this).data('address'),
                id:$(_this).data('id')
            });
        });
    
        $('#selectAddress .address-list .address .right .delAddress').unbind('click').bind('click',function(e){
            var id = $(this).data('id');
            delAddress(id,this);
            e.stopPropagation();
        });
        $('#selectAddress .address-list .address .right .editAddress').unbind('click').bind('click',function(e){
            var id = $(this).data('id');
            setAddAddress(id);
            e.stopPropagation();
        });
    });
}

//修改当前藏品时时显示关注数
function followUserCount(num){
    var collCount = parseInt($('#collCount').text());
    var currentCollCount = collCount + num;
    $('#collCount').text(currentCollCount);
}

//设置添加地址
function setAddAddress(id,isDefault){
    $('#addAddressContainer .header .return').unbind('click').bind('click',function(){
        
    });
    $('#addAddressContainer .weui-input').val('');
    if(isDefault){
        $('#isDefault').val('true');
    } else {
        $('#isDefault').val('false');
    }
    if(id && id != ''){
        $('#adreeId').val(id);
        $.post('/antique/api/userAddress/query',{
            token:getCookie('token'),
            id:id
        },function(result){
            var address = result.data;
            $('#name').val(address.name);
            $('#area-choise').val(address.areaNames);
            $('#address').val(address.address);
            $('#phone').val(address.phone);
        })
        $('#showTooltips').text('确认修改');
    } else {
        $('#adreeId').val('');
        $('#showTooltips').text('确认添加');
    }
    $("#addAddressContainer").popup();
    $("#area-choise").cityPicker({
    title: "选择城市",
        onChange: function (picker, values, displayValues) {
            var name = displayValues[0] + " " + displayValues[1] + " " + displayValues[2];
            $("#area").val(name);
        }
    });
}

//删除收货地址
function delAddress(id,_this){
    $.confirm("您确定要删除该收货地址吗?", "确认删除?", function() {
        $.post('/antique/api/userAddress/delete_address',{
            token:getCookie('token'),
            id:id
        },function(result){
            $(_this).parent().parent().remove();
            return false;
        });
    });
}

var addAddressLoading = false;
function puilcPro(){
    if(addAddressLoading){
        return false;
    } else {
        addAddressLoading = true;
    }
    var id = $("#adreeId").val();
    var name = $("#name").val();
    var area = $("#area").val();
    var address = $("#address").val();
    var phone = $("#phone").val();   
    var isDefault = $('#isDefault').val();
    if (name == ''){
        $.toast("名称不能为空", "cancel");
        return;
    }
    if (area == ''){
        $.toast("城市不能为空", "cancel");
        return;
    }
    if (address == ''){
        $.toast("地址不能为空", "cancel");
        return;
    }
    if (phone == ''){
        $.toast("电话不能为空", "cancel");
        return;
    }   
    var params = {};
    params.id = id;
    params.name = name;
    params.areaNames = area;
    params.address = address;
    params.phone = phone;
    if(isDefault && isDefault == 'true')params.isDefault = 1;
    params.token = getCookie('token');
    if (id && id != ''){
        upPro(params);
    } else {
        addPro(params);
    }
} 

function addPro(params){
    delete params.id;
    $.ajax({
        type:'POST',
        url:"/antique/api/userAddress/add_address",
        data: params,
        dataType:"json",
        success:function(res){
            if (res.code == 0){
                // 如果是第一条收货地址信息就设置
                if(params.isDefault == 1){
                    $.post('/antique/api/userAddress/set_address_default',{
                        token:getCookie('token'),
                        id:res.data.id,
                        isDefault:1
                    })
                }
                setAddressList();
                $.toast("成功");
            } else {
                $.toast(res.message, "cancel");
            }    
            addAddressLoading = false;        
        }
    });
}

function upPro(params){
    $.ajax({
        type:'POST',
        url:"/antique/api/userAddress/update_address",
        data: params,
        dataType:"json",
        success:function(res){
            if (res.code == 0){
                setAddressList();
                $.toast("成功");
            } else {
                $.toast(res.message, "cancel");
            }   
            addAddressLoading = false;         
        }
    });
}



